<?php

class Helper_Menu
{
	protected $_data = null;

	protected $_name = null;

	public function render($data)
	{
		if (is_string($data))
		{
			$data = DbNosql::inst() -> findOne('agilet_menus', array('_id' => $data));
		}

		if (empty($data))
		{
			return '';
		}

		$this -> _name = $data['_id'];

		$xhtml = array();

		foreach ($data['items'] as $item)
		{
			$xhtml[] = $this -> renderItem($item, 0);
		}
		return '<ul class="menu">' . implode(PHP_EOL, $xhtml) . '</ul>';
	}

	public function renderSubMenu($items, $level = 0)
	{
		$xhtml = array();
		foreach ($items as $item)
		{
			$xhtml[] = $this -> renderItem($item, $level);
		}
		return '<ul>' . implode(PHP_EOL, $xhtml) . '</ul>';

	}

	public function renderItem($item, $level = 0)
	{

		if ($item['type'] == 'static')
		{
			$item['url'] = Agilet::getUrl($item['path'], $item['params']);
		}
		else
		if ($item['type'] == 'callback')
		{
			list($class, $method) = explode($item['callback']);
			$item = call_user_func(array(
				$class,
				$method
			), $item);
			if ($item == false)
			{
				return '';
			}
		}

		$ul = '';
		if (isset($item['items']) && $item['items'])
		{
			$ul = $this -> renderSubMenu($item['items'], $level + 1);
		}
		$cls = $this -> _name . '-' . $item['id'];
		return '<li class="' . $cls . '"><a href="' . $item['url'] . '"><span>' . $item['label'] . '</span></a>' . $ul . '</li>';
	}

}
